<template>
  <div class="product-plan-wrap table-gl-w">
    <a-tabs @change="changeStatus" size="mini">
      <a-tab-pane key="" title="全部" />
      <template v-for="tab in Object.values(tabsMap)" :key="tab.key">
        <a-tab-pane v-if="tab.key" :key="tab.key">
          <template #title>
            <span>{{ tab.title }}</span>
            <span>({{ countMap[tab.key] || 0 }})</span>
          </template>
        </a-tab-pane>
      </template>
    </a-tabs>

    <div class="search-w table-filter-form">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getTableList">
        <template #headerLeft>
          <a-space>
            <a-button class="gray-outline" @click="submitDelete(selectIds)" v-if="searchVal.status != 20 && searchVal.status != 30 && $authPass('procurement.production.plan.cancel')">删除</a-button>
            <a-button v-if="searchVal.status === 10 && $authPass('procurement.production.plan.start')" type="primary" size="medium" @click="startProduction(selectIds)">开始生产</a-button>
            <a-button v-if="searchVal.status === 20 && $authPass('procurement.production.plan.close')" type="primary" size="medium" @click="openStopProduction(selectIds)">终止生产</a-button>
            <a-button v-if="searchVal.status === 20 && $authPass('procurement.production.plan.inbound')" type="primary" size="medium" @click="openInStorageProduction(selectIds)">生产入库</a-button>
            <a-button v-if="$authPass('procurement.production.plan.print')" class="gray-outline" size="medium" @click="toPrintPDF(selectIds)">打印</a-button>
          </a-space>
        </template>
        <template #tableBody>
          <a-table
            class="table-singe-line show-border-table"
            ref="tableRef"
            row-key="id"
            :loading="tableLoading"
            @selection-change="selectColumn"
            :row-selection="rowSelection"
            :data="tableList"
            :scroll="{
              x: '100%',
              y: '100%',
            }"
            size="mini"
            :pagination="false"
          >
            <template #columns>
              <a-table-column data-index="sort" title="序号" :width="45" fixed="left" key="sort">
                <template #cell="{ rowIndex }">
                  <p>{{ rowIndex + 1 }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="billNo" title="计划单号" :width="130" fixed="left" key="billNo">
                <template #cell="{ record }">
                  <a-space :size="4">
                    <p class="highlight cursor" @click="openDetail(record)">{{ record.billNo }}</p>
                    <CopyText :val="record.billNo" class="popup-edit-icon-hover" />
                  </a-space>
                </template>
              </a-table-column>
              <a-table-column data-index="img" title="图片" :width="60" fixed="left" key="img">
                <template #cell="{ record }">
                  <ImgPopover :src="getFirstImg(record.productImg)">
                    <template #con>
                      <a-image width="40" height="40" fit="contain" :src="getFirstImg(record.productImg)" />
                    </template>
                  </ImgPopover>
                </template>
              </a-table-column>
              <a-table-column data-index="sku" title="SKU" :width="130" fixed="left" key="sku">
                <template #cell="{ record }">
                  <p class="highlight">{{ record.sku }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="productSpecs" title="SKU规格" :width="100" key="productSpecs">
                <template #cell="{ record }">
                  <TextLimit :val="getProductSpecs(record)" />
                </template>
              </a-table-column>
              <a-table-column data-index="purchaseSpecsArr" title="生产参数" :width="100" key="purchaseSpecsArr">
                <template #cell="{ record }">
                  <PurchasePropPopover v-if="record.purchaseSpecsArr" :purchaseSpecsArr="record.purchaseSpecsArr" />
                </template>
              </a-table-column>
              <a-table-column data-index="material" title="材质" :width="60" key="material">
                <template #cell="{ record }">
                  <p>{{ getMaterial(record) }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="productType" title="类型" :width="60" key="productType">
                <template #cell="{ record }">
                  <p>{{ productTypeMap[record.productType] || record.productType }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="businessNo" title="关联单号" :width="150" key="businessNo">
                <template #cell="{ record }">
                  <a-space :size="4">
                    <p class="highlight">{{ record.businessNo }}</p>
                    <CopyText :val="record.businessNo" class="popup-edit-icon-hover" />
                  </a-space>
                </template>
              </a-table-column>
              <a-table-column data-index="purchaseCompanyName" title="客户" :width="100" key="purchaseCompanyName" />
              <a-table-column data-index="productionAmt" title="生产数量" :width="70" key="productionAmt" />
              <a-table-column data-index="warehouseRealAmt" title="生产入库数" :width="80" key="warehouseRealAmt" />
              <a-table-column data-index="warehouseName" title="生产入库仓" :width="100" key="warehouseName" />
              <a-table-column title="计划创建时间" :width="140" key="gmtCreate">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.gmtCreate) }}</p>
                </template>
              </a-table-column>
              <a-table-column title="接单日期" :width="90" key="gmtAccept">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.gmtAccept, 'YYYY-MM-DD') }}</p>
                </template>
              </a-table-column>
              <a-table-column title="期望交货日期" :width="90" key="gmtExpectDelivery">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.gmtExpectDelivery, 'YYYY-MM-DD') }}</p>
                </template>
              </a-table-column>
              <a-table-column title="开始时间" :width="140" key="gmtProduction">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.gmtProduction) }}</p>
                </template>
              </a-table-column>
              <a-table-column title="状态" :width="70" key="status">
                <template #cell="{ record }">
                  <p>{{ tabsMap[record.status] ? tabsMap[record.status].title : record.status }}</p>
                </template>
              </a-table-column>

              <a-table-column title="操作" :width="140" fixed="right" key="handle" v-if="searchVal.status != 30">
                <template #cell="{ record }">
                  <a-space>
                    <a-popconfirm content="确认开始生产？" v-if="record.status == 10 && $authPass('procurement.production.plan.start')" @ok="requestStartProduction([record.id])" type="warning">
                      <a-button type="text">开始生产</a-button>
                    </a-popconfirm>
                    <a-button v-if="record.status == 10 && $authPass('procurement.production.plan.update')" type="text" @click="openEdit(record)">编辑</a-button>
                    <a-button v-if="record.status == 20 && $authPass('procurement.production.plan.inbound')" type="text" @click="openInStorageProduction([record.id])">生产入库</a-button>
                    <a-button v-if="record.status == 20 && $authPass('procurement.production.plan.close')" type="text" @click="openStopProduction([record.id])">终止生产</a-button>
                  </a-space>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <!-- 終止计划 -->
  <StopProductionPlan v-if="showStopProduction" :isShow="showStopProduction" :list="selectRows" @closed="showStopProduction = false" @success="getListAndCount" />
  <!-- 生产入库 -->
  <InStorageProductionPlan v-if="showInStorageProduction" :isShow="showInStorageProduction" :list="selectRows" @closed="showInStorageProduction = false" @success="getListAndCount" />
  <!-- 编辑 -->
  <EditProductPlan v-if="showEditDetail" :isShow="showEditDetail" :currentId="currentData.id" @closed="showEditDetail = false" @success="getListAndCount" />
  <!-- 详情 -->
  <ProductPlanDetail v-if="showDetail" :isShow="showDetail" :currentData="currentData" @closed="showDetail = false" @success="getListAndCount" @openEdit="openEdit(currentData)" @openInStorage="openInStorageProduction([currentData.id])" @openStop="openStopProduction([currentData.id])" />
</template>
<script lang="ts" setup>
  import { ref, onMounted, reactive } from 'vue'
  import FilterTable from '@/components/TableFilter.vue'
  import { FilterTableItem } from '@/types/components'
  import TableWrap from '@/components/TableWrap.vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import PurchasePropPopover from '../components/purchasePropPopover.vue'
  import StopProductionPlan from '../components/stopProductionPlan.vue'
  import InStorageProductionPlan from '../components/inStorageProductionPlan.vue'
  import EditProductPlan from '../components/editProductPlan.vue'
  import ProductPlanDetail from '../components/productPlanDetail.vue'
  import { findProductionPlanPage, findProductionPlanCountStatus, cancelProductionPlan, startProductionPlan } from '@/api/purchaseApplication'
  import { parseJson } from '@/utils'
  import { useRouter } from 'vue-router'

  onMounted(() => {
    getListAndCount()
  })
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any

  const filterItem = ref<Array<FilterTableItem>>([
    {
      type: 'input_keyword',
      key: 'billNos',
      keyItems: [
        { label: '关联单号', value: 'businessNos' },
        { label: '计划单号', value: 'billNos' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 200,
      isMultiple: true,
    },
    {
      type: 'input_keyword',
      key: 'skus',
      keyItems: [
        { label: 'SKU', value: 'skus' },
        { label: '产品名称', value: 'productName' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 200,
      isMultiple: true,
    },
    {
      type: 'input_search',
      key: 'purchaseCompanyName',
      value: ref(),
      placeholder: '',
      label: '客户公司名称',
      width: 200,
    },
  ])
  const tabsMap = {
    0: { key: 0, title: '作废' },
    10: { key: 10, title: '待生产' },
    20: { key: 20, title: '生产中' },
    30: { key: 30, title: '已完成' },
  }
  const countMap = ref<any>({})
  let searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
    status: '',
  })
  const total = ref(0)
  const tableLoading = ref(false)
  const showInStorageProduction = ref(false)
  const tableList = ref<Array<any>>([])
  const selectIds = ref([])
  const selectRows = ref<any>([])
  const tableRef = ref()
  const filterData = ref<any>({})
  const tableListMap = ref({})
  const showStopProduction = ref(false)
  const currentData = ref<any>({})
  const showEditDetail = ref(false)
  const router = useRouter()
  const showDetail = ref(false)
  const productTypeMap = {
    1: '普货',
    2: '打样',
    3: '定制',
  }

  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }
  // 去打印
  function toPrintPDF(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择生产计划')
      return
    }
    window.sessionStorage.setItem('productPlanId', ids.join(','))
    router.push('/purchaseApplication/supplier/productPlanPrintPDF')
  }

  // 切换状态
  function changeStatus(status: number | string) {
    searchVal.value.status = status
    searchVal.value.pageNum = 1
    getTableList()
  }
  // 查询列表和数量合计
  function getListAndCount() {
    getTableList()
    getCountList()
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }
  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 通过条件查询用户列表
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }
  // 查询各状态下数量合计
  async function getCountList() {
    const res: any = await findProductionPlanCountStatus()
    let counts = res?.data || []
    countMap.value = {}
    counts.forEach((el: any) => {
      countMap.value[el.status] = el.totalCount
    })
  }
  // 获取商品列表
  async function getTableList() {
    let params = {
      ...searchVal.value,
      ...filterData.value,
    }
    tableLoading.value = true
    const res: any = await findProductionPlanPage(params)
    tableRef.value.selectAll(false)
    tableLoading.value = false
    tableList.value = res?.data?.records || []
    total.value = res?.data?.total || 0
    tableListMap.value = {}
    tableList.value.forEach((el: any) => {
      if (!parseJson(el.purchaseSpecs, null)) {
        let purchaseSpecs = el.purchaseSpecs?.split('\n')
        el.purchaseSpecsArr = purchaseSpecs.map((prop: string) => {
          let propArr = prop ? prop.split('：') : []
          return {
            name: propArr[0],
            purchaseValue: propArr[1],
          }
        })
      }
      tableListMap.value[el.id] = el
    })
  }
  // 获取材质
  function getMaterial(row: any) {
    let propArr = row.purchaseSpecsArr || []
    return propArr.find((el: any) => el.name == '材质')?.purchaseValue
  }
  // 删除计划
  async function submitDelete(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择生产计划')
      return
    }
    Modal.confirm({
      title: '删除',
      content: `再次确认删除选中的生产计划？`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await cancelProductionPlan({ ids: ids })
        if (res) {
          Message.success('删除成功')
          getListAndCount()
        }
      },
    })
  }
  // 开始生产
  function startProduction(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择生产计划')
      return
    }
    Modal.confirm({
      title: '开始生产',
      content: `再次确认开始生产选中的计划？`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: () => {
        requestStartProduction(ids)
      },
    })
  }
  async function requestStartProduction(ids: Array<string>) {
    const res: any = await startProductionPlan({ ids: ids })
    if (res) {
      Message.success('已提交生产')
      getListAndCount()
    }
  }

  // 终止生产
  function openStopProduction(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择生产计划')
      return
    }
    selectRows.value = []
    ids.map((id) => {
      selectRows.value.push(tableListMap.value[id])
    })
    showStopProduction.value = true
  }
  // 生产入库
  function openInStorageProduction(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择生产计划')
      return
    }
    selectRows.value = []
    ids.map((id) => {
      selectRows.value.push(tableListMap.value[id])
    })
    showInStorageProduction.value = true
  }
  function openEdit(row: any) {
    currentData.value = row
    showEditDetail.value = true
  }
  function openDetail(row: any) {
    currentData.value = row
    showDetail.value = true
  }

  function getFirstImg(str: string) {
    let arr = str.split(',')
    return arr[0]
  }
</script>
<style lang="less" scoped>
  :deep(.arco-tabs-nav-tab) {
    background-color: #fff;
  }
</style>
